package modules.arc.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.hibernate.criterion.Restrictions;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import luxing.common.controller.BaseController;
import luxing.common.service.CloudStorageService;
import luxing.constant.StorageConfig;
import luxing.exception.BusinessException;
import luxing.hibernate.CriteriaQuery;
import luxing.util.CriteriaQueryUtil;
import luxing.util.DateUtil;
import luxing.util.LoginUserUtil;
import luxing.util.ValidatorUtil;
import luxing.web.model.DataGrid;
import luxing.web.model.Result;
import luxing.web.model.SortDirection;
import luxing.web.model.ValidResult;
import modules.arc.entity.ArcExt;
import modules.arc.entity.Driver;
import modules.arc.entity.Owner;
import modules.arc.entity.Vehicle;
import modules.arc.entity.VehicleExt;
import modules.arc.entity.VehiclePic;
import modules.arc.service.ArcExtService;
import modules.arc.service.DriverService;
import modules.arc.service.OwnerService;
import modules.arc.service.VehicleService;
import modules.fin.entity.Income;
import modules.fin.service.IncomeService;
import modules.sys.entity.Log;
import modules.sys.service.LogService;
import modules.sys.service.RegionService;
import modules.warn.entity.WarnType;
import modules.warn.service.WarnTypeService;

/**
 * 
 * @author zzc
 *
 */
@Controller
@RequestMapping("/vehicleController")
public class VehicleController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(VehicleController.class);

	@Autowired
	private LogService logService;
	@Autowired
	private VehicleService vehicleService;
	@Autowired
	private ArcExtService arcExtService;
	@Autowired
	private WarnTypeService warnTypeService;
	@Autowired
	private IncomeService incomeService;
	@Autowired
	private CloudStorageService cloudStorageService;
	@Autowired
	private RegionService regionService;
	@Autowired
	private OwnerService ownerService;
	@Autowired
	private DriverService driverService;

	/**
	 * 列表页面
	 * 
	 * @return
	 */
	@RequestMapping(params = "index")
	public ModelAndView index(HttpServletRequest request) {
		return new ModelAndView("modules/arc/vehicle-list");
	}

	/**
	 * 图片列表页面
	 * 
	 * @return
	 */
	@RequestMapping(params = "picIndex")
	public ModelAndView picIndex(HttpServletRequest request) {
		request.setAttribute("vehicleId", request.getParameter("vehicleId"));
		return new ModelAndView("modules/arc/vehiclePic-list");
	}

	/**
	 * 选择页面
	 * 
	 * @return
	 */
	@RequestMapping(params = "select")
	public ModelAndView select(HttpServletRequest request) {
		request.setAttribute("ownerId", request.getParameter("ownerId"));
		request.setAttribute("type", request.getParameter("type"));
		return new ModelAndView("modules/arc/vehicle-select");
	}

	/**
	 * 多选页面
	 * 
	 * @return
	 */
	@RequestMapping(params = "selectMore")
	public ModelAndView selectMore(HttpServletRequest request) {
		request.setAttribute("vehicleId", request.getParameter("vehicleId"));
		request.setAttribute("vehiclePlateNumber", request.getParameter("vehiclePlateNumber"));
		return new ModelAndView("modules/arc/vehicle-selectMore");
	}

	/**
	 * 列表数据
	 * 
	 * @param vehicle
	 * @param request
	 * @param response
	 * @param dataGrid
	 */
	@RequestMapping(params = "list")
	public void list(Vehicle vehicle, HttpServletRequest request, HttpServletResponse response,
			DataGrid dataGrid) {
		try {
			CriteriaQuery cq = new CriteriaQuery(Vehicle.class, dataGrid);
			CriteriaQueryUtil.assembling(cq, vehicle, request.getParameterMap());
			// 状态
			String status = request.getParameter("status");
			if (StringUtils.isBlank(status)) {
				cq.notEq("status", Vehicle.STATUS_DISABLE);
			}
			cq.add();
			vehicleService.listByPage(cq, true);
			listView(response, dataGrid);
		} catch (Exception e) {
			logger.error("车辆查询失败", e);
			throw new BusinessException("车辆查询失败", e);
		}
	}

	/**
	 * 选择列表数据
	 * 
	 * @param vehicle
	 * @param request
	 * @param response
	 * @param dataGrid
	 */
	@RequestMapping(params = "selectList")
	public void selectList(Vehicle vehicle, HttpServletRequest request, HttpServletResponse response,
			DataGrid dataGrid) {
		try {
			CriteriaQuery cq = new CriteriaQuery(Vehicle.class, dataGrid);
			CriteriaQueryUtil.assembling(cq, vehicle, request.getParameterMap());
			String noPlateNumberOwner = request.getParameter("noPlateNumberOwner");
			if (StringUtils.isNotBlank(noPlateNumberOwner)) {
				cq.createAlias("owner", "owner");
				cq.add(Restrictions.or(Restrictions.like("sn", "%" + noPlateNumberOwner + "%"),
						Restrictions.like("plateNumber", "%" + noPlateNumberOwner + "%"),
						Restrictions.like("owner.name", "%" + noPlateNumberOwner + "%")));

			}
			// 状态
			String status = request.getParameter("status");
			if (StringUtils.isBlank(status)) {
				cq.notEq("status", Vehicle.STATUS_DISABLE);
			}
			cq.add();
			vehicleService.listByPage(cq, true);
			listView(response, dataGrid);
		} catch (Exception e) {
			logger.error("车辆查询失败", e);
			throw new BusinessException("车辆查询失败", e);
		}
	}

	/**
	 * 司机-车辆增加列表数据
	 * 
	 * @param vehicle
	 * @param request
	 * @param response
	 * @param dataGrid
	 */
	@RequestMapping(params = "driverVehicleAddList")
	public void driverVehicleAddList(Vehicle vehicle, HttpServletRequest request, HttpServletResponse response,
			DataGrid dataGrid) {
		try {
			CriteriaQuery cq = new CriteriaQuery(Vehicle.class, dataGrid);
			CriteriaQueryUtil.assembling(cq, vehicle, request.getParameterMap());
			cq.addOrder("sn", SortDirection.asc);
			cq.add();
			vehicleService.listByPage(cq, true);
			listView(response, dataGrid);
		} catch (Exception e) {
			logger.error("车辆查询失败", e);
			throw new BusinessException("车辆查询失败", e);
		}
	}

	/**
	 * 车辆-图片列表数据
	 * 
	 * @param ownerPic
	 * @param request
	 * @param response
	 * @param dataGrid
	 */
	@RequestMapping(params = "picList")
	public void picList(VehiclePic vehiclePic, HttpServletRequest request, HttpServletResponse response,
			DataGrid dataGrid) {
		try {
			CriteriaQuery cq = new CriteriaQuery(VehiclePic.class, dataGrid);
			CriteriaQueryUtil.assembling(cq, vehiclePic, request.getParameterMap());
			cq.eq("vehicle.id", request.getParameter("vehicleId"));
			cq.add();
			vehicleService.listByPage(cq, true);
			for (Object obj : dataGrid.getResults()) {
				VehiclePic entity = (VehiclePic) obj;
				String thumbUrl = cloudStorageService.generatePresignedUrl(StorageConfig.bucketVehicle,
						entity.getThumbPath());
				String url = cloudStorageService.generatePresignedUrl(StorageConfig.bucketVehicle, entity.getPath());
				entity.setThumbUrl(thumbUrl);
				entity.setUrl(url);
			}
			listView(response, dataGrid);
		} catch (Exception e) {
			logger.error("车辆图片查询失败", e);
			throw new BusinessException("车辆图片查询失败", e);
		}
	}

	/**
	 * 增加页面
	 * 
	 * @return
	 */
	@RequestMapping(params = "goAdd")
	public ModelAndView goAdd(HttpServletRequest req) {
		String licensePlate = regionService.getLicensePlate(LoginUserUtil.getLoginUser().getTenantId());
		req.setAttribute("licensePlate", licensePlate);
		return new ModelAndView("modules/arc/vehicle-add");
	}

	/**
	 * 图片增加页面
	 * 
	 * @return
	 */
	@RequestMapping(params = "goAddPic")
	public ModelAndView goAddPic(HttpServletRequest req) {
		if (StringUtils.isNotBlank(req.getParameter("vehicleId"))) {
			Vehicle vehicle = vehicleService.get(Vehicle.class, req.getParameter("vehicleId"));
			req.setAttribute("vehiclePage", vehicle);
		}
		return new ModelAndView("modules/arc/vehiclePic-add");
	}

	/**
	 * 修改页面
	 * 
	 * @return
	 */
	@RequestMapping(params = "goUpdate")
	public ModelAndView goUpdate(Vehicle vehicle, HttpServletRequest req) {
		if (StringUtils.isNotBlank(vehicle.getId())) {
			vehicle = vehicleService.get(Vehicle.class, vehicle.getId());
			// 司机信息
			String driverId = "", driverName = "";
			for (Driver driver : vehicle.getDriverList()) {
				driverId = driverId.concat(driver.getId()).concat(",");
				driverName = driverName.concat(driver.getName()).concat(",");
			}
			if (driverId.endsWith(",")) {
				driverId = driverId.substring(0, driverId.length() - 1);
			}
			if (driverName.endsWith(",")) {
				driverName = driverName.substring(0, driverName.length() - 1);
			}
			req.setAttribute("driverId", driverId);
			req.setAttribute("driverName", driverName);
			// 关联车辆
			if (StringUtils.isNotBlank(vehicle.getRelationVehicleId())) {
				Vehicle relationVehicle = vehicleService.get(Vehicle.class, vehicle.getRelationVehicleId());
				if (relationVehicle != null) {
					req.setAttribute("relationVehiclePlateNumber", relationVehicle.getPlateNumber());
				} else {
					vehicle.setRelationVehicleId(null);
				}
			}
			req.setAttribute("vehiclePage", vehicle);
		}
		return new ModelAndView("modules/arc/vehicle-update");
	}

	/**
	 * 查看页面
	 * 
	 * @return
	 */
	@RequestMapping(params = "goDetail")
	public ModelAndView goDetail(Vehicle vehicle, HttpServletRequest req) {
		if (StringUtils.isNotBlank(vehicle.getId())) {
			vehicle = vehicleService.get(Vehicle.class, vehicle.getId());
			// 司机信息
			String driverId = "", driverName = "";
			for (Driver driver : vehicle.getDriverList()) {
				driverId = driverId.concat(driver.getId()).concat(",");
				driverName = driverName.concat(driver.getName()).concat(",");
			}
			if (driverId.endsWith(",")) {
				driverId = driverId.substring(0, driverId.length() - 2);
			}
			if (driverName.endsWith(",")) {
				driverName = driverName.substring(0, driverName.length() - 2);
			}
			req.setAttribute("driverId", driverId);
			req.setAttribute("driverName", driverName);
			// 关联车辆
			if (StringUtils.isNotBlank(vehicle.getRelationVehicleId())) {
				Vehicle relationVehicle = vehicleService.get(Vehicle.class, vehicle.getRelationVehicleId());
				if (relationVehicle != null) {
					req.setAttribute("relationVehiclePlateNumber", relationVehicle.getPlateNumber());
				} else {
					vehicle.setRelationVehicleId(null);
				}
			}
			req.setAttribute("vehiclePage", vehicle);
		}
		return new ModelAndView("modules/arc/vehicle-detail");
	}

	/**
	 * 注销页面
	 * 
	 * @return
	 */
	@RequestMapping(params = "goDisable")
	public ModelAndView goDisable(Vehicle vehicle, HttpServletRequest req) {
		if (StringUtils.isNotBlank(vehicle.getId())) {
			vehicle = vehicleService.get(Vehicle.class, vehicle.getId());
			req.setAttribute("vehiclePage", vehicle);
		}
		return new ModelAndView("modules/arc/vehicle-disable");
	}

	/**
	 * 查看页面
	 * 
	 * @return
	 */
	@RequestMapping(params = "goPrint")
	public ModelAndView goPrint(Vehicle vehicle, HttpServletRequest req) {
		if (StringUtils.isNotBlank(vehicle.getId())) {
			vehicle = vehicleService.get(Vehicle.class, vehicle.getId());
			// 司机信息
			String driverId = "", driverName = "";
			for (Driver driver : vehicle.getDriverList()) {
				driverId = driverId.concat(driver.getId()).concat(",");
				driverName = driverName.concat(driver.getName()).concat(",");
			}
			if (driverId.endsWith(",")) {
				driverId = driverId.substring(0, driverId.length() - 2);
			}
			if (driverName.endsWith(",")) {
				driverName = driverName.substring(0, driverName.length() - 2);
			}
			req.setAttribute("driverId", driverId);
			req.setAttribute("driverName", driverName);
			// 关联车辆
			if (StringUtils.isNotBlank(vehicle.getRelationVehicleId())) {
				Vehicle relationVehicle = vehicleService.get(Vehicle.class, vehicle.getRelationVehicleId());
				if (relationVehicle != null) {
					req.setAttribute("relationVehiclePlateNumber", relationVehicle.getPlateNumber());
				} else {
					vehicle.setRelationVehicleId(null);
				}
			}
			req.setAttribute("vehiclePage", vehicle);
		}
		return new ModelAndView("modules/arc/vehicle-print");
	}

	/**
	 * 扩展信息页面
	 * 
	 * @return
	 */
	@RequestMapping(params = "ext")
	public ModelAndView ext(HttpServletRequest req) {
		req.setAttribute("id", req.getParameter("id"));
		return new ModelAndView("modules/arc/vehicle-ext");
	}

	/**
	 * 扩展信息页面
	 * 
	 * @return
	 */
	@RequestMapping(params = "warn")
	public ModelAndView warn(HttpServletRequest req) {
		req.setAttribute("id", req.getParameter("id"));
		return new ModelAndView("modules/arc/vehicle-warn");
	}

	/**
	 * 增加
	 * 
	 * @param vehicle
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "doAdd")
	@ResponseBody
	public Result doAdd(Vehicle vehicle, HttpServletRequest request) {
		String msg = null;
		try {
			// 司机信息
			List<Driver> driverList = new ArrayList<Driver>();
			String driverId = request.getParameter("driverId");
			if (StringUtils.isNotBlank(driverId)) {
				String[] driverIdArray = driverId.split(",");
				for (String id : driverIdArray) {
					Driver driver = new Driver();
					driver.setId(id);
					driverList.add(driver);
				}
			}
			vehicle.setDriverList(driverList);
			// 关联车辆
			if (vehicle.getType().equals(Vehicle.TYPE_WHOLE)) {
				vehicle.setRelationVehicleId(null);
			}
			// bean校验
			msg = ValidatorUtil.validate(vehicle);
			if (StringUtils.isNotBlank(msg)) {
				return Result.error(msg);
			}
			vehicleService.save(vehicle, arcExtService.listByType(ArcExt.TYPE_VEHICLE),
					warnTypeService.listByStatus(WarnType.STATUS_ENABLE), request);
			msg = "车辆\"" + vehicle.getPlateNumber() + "\"增加成功";
			logger.info(msg);
			logService.addLogInfo(msg, Log.OPERATE_ADD);
		} catch (Exception e) {
			msg = "车辆\"" + vehicle.getPlateNumber() + "\"增加失败";
			logger.error(msg, e);
			throw new BusinessException(msg, e);
		}
		return Result.success(msg);
	}

	/**
	 * 增加图片
	 * 
	 * @param vehicle
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "doAddPic")
	@ResponseBody
	public Result doAddPic(VehiclePic vehiclePic, HttpServletRequest request) {
		String msg = null;
		try {
			String[] pathArray = vehiclePic.getPath().split(",");
			String[] thumbPathArray = vehiclePic.getThumbPath().split(",");
			if (pathArray == null || thumbPathArray == null || pathArray.length != thumbPathArray.length) {
				msg = "车辆\"" + vehiclePic.getVehicle().getPlateNumber() + "\"图片上传失败";
				return Result.error(msg);
			}
			for (int i = 0; i < pathArray.length; i++) {
				VehiclePic entity = new VehiclePic();
				entity.setVehicle(vehiclePic.getVehicle());
				entity.setType(vehiclePic.getType());
				entity.setPath(pathArray[i]);
				entity.setThumbPath(thumbPathArray[i]);
				// bean校验
				msg = ValidatorUtil.validate(vehiclePic);
				if (StringUtils.isNotBlank(msg)) {
					return Result.error(msg);
				}
				vehicleService.save(entity);
			}
			msg = "车辆\"" + vehiclePic.getVehicle().getPlateNumber() + "\"图片增加成功";
			logger.info(msg);
			logService.addLogInfo(msg, Log.OPERATE_ADD);
		} catch (Exception e) {
			msg = "车辆\"" + vehiclePic.getVehicle().getPlateNumber() + "\"图片增加失败";
			logger.error(msg, e);
			throw new BusinessException(msg, e);
		}
		return Result.success(msg);
	}

	/**
	 * 上传图片
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "uploadPic")
	@ResponseBody
	public Result uploadPic(HttpServletRequest request) {
		Result result = new Result();
		try {
			String vehicleId = request.getParameter("vehicleId");
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			MultipartFile file = multipartRequest.getFile("file");// 获取上传文件对象
			// 文件名后缀
			String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
			String picName = DateUtil.dateToStr(new Date(), "yyyyMMdd") + DateUtil.dateToStr(new Date(), "HHmmssS")
					+ UUID.randomUUID().toString().replaceAll("-", "").substring(0, 5) + "." + suffix;
			// 路径
			String path = LoginUserUtil.getLoginUser().getTenantId() + "/" + vehicleId + "/" + picName;
			// 缩略图路径
			String thumbPath = LoginUserUtil.getLoginUser().getTenantId() + "/" + vehicleId + "/thumb/" + picName;
			cloudStorageService.uploadCompress(file, StorageConfig.bucketVehicle, suffix, path, thumbPath);
			// 返回信息
			Map<String, Object> attributes = new HashMap<String, Object>();
			attributes.put("path", path);
			attributes.put("thumbPath", thumbPath);
			result.setAttributes(attributes);
		} catch (Exception e) {
			logger.error(e);
			throw new BusinessException(e);
		}
		return result;
	}

	/**
	 * 下载图片
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "downloadPic")
	@ResponseBody
	public void downloadPic(HttpServletRequest request, HttpServletResponse response) {
		try {
			VehiclePic vehiclePic = vehicleService.get(VehiclePic.class, request.getParameter("id"));
			String imgUrl = cloudStorageService.generatePresignedUrl(StorageConfig.bucketVehicle, vehiclePic.getPath());
			String fileName = imgUrl.substring(imgUrl.lastIndexOf('/') + 1, imgUrl.lastIndexOf("?"));
			URL url = new URL(imgUrl);
			response.setContentType("application/x-msdownload;");
			response.setHeader("Content-disposition",
					"attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1"));
			response.setHeader("Content-Length", String.valueOf(url.openConnection().getContentLength()));
			BufferedInputStream is = new BufferedInputStream(url.openStream());
			BufferedOutputStream os = new BufferedOutputStream(response.getOutputStream());
			byte[] buff = new byte[1024];
			int bytesRead;
			while (-1 != (bytesRead = is.read(buff, 0, buff.length))) {
				os.write(buff, 0, bytesRead);
			}
			is.close();
			os.close();
		} catch (Exception e) {
			logger.error(e);
			throw new BusinessException(e);
		}
	}

	/**
	 * 删除图片
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "delPic")
	@ResponseBody
	public void delPic(HttpServletRequest request) {
		try {
			String thumbPath = request.getParameter("thumbPath");
			String path = request.getParameter("path");
			cloudStorageService.delete(StorageConfig.bucketVehicle, thumbPath);
			cloudStorageService.delete(StorageConfig.bucketVehicle, path);
		} catch (Exception e) {
			logger.error(e);
			throw new BusinessException(e);
		}
	}

	/**
	 * 修改
	 * 
	 * @param vehicle
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "doUpdate")
	@ResponseBody
	public Result doUpdate(Vehicle vehicle, HttpServletRequest request) {
		String msg = null;
		try {
			Vehicle vehicleDB = vehicleService.get(Vehicle.class, vehicle.getId());
			// 编号、类型、普货/危货、登记日期、备注
			vehicleDB.setSn(vehicle.getSn());
			vehicleDB.setType(vehicle.getType());
			vehicleDB.setGeneralDanger(vehicle.getGeneralDanger());
			vehicleDB.setRegisterDate(vehicle.getRegisterDate());
			vehicleDB.setRemarks(vehicle.getRemarks());
			/** 车牌变更 */
			if (!StringUtils.equals(vehicleDB.getPlateNumber(), vehicle.getPlateNumber())) {
				System.out.println("----------------------车牌变更");
			}
			vehicleDB.setPlateNumber(vehicle.getPlateNumber());
			/** 责任人变更 */
			if (!StringUtils.equals(vehicleDB.getOwner().getId(), vehicle.getOwner().getId())) {
				System.out.println("----------------------责任人变更");
			}
			vehicleDB.setOwner(vehicle.getOwner());
			vehicleDB.setStatus(vehicle.getStatus());
			// 司机信息
			List<Driver> driverList = new ArrayList<Driver>();
			String driverId = request.getParameter("driverId");
			if (StringUtils.isNotBlank(driverId)) {
				String[] driverIdArray = driverId.split(",");
				for (String id : driverIdArray) {
					Driver driver = new Driver();
					driver.setId(id);
					driverList.add(driver);
				}
			}
			vehicleDB.setDriverList(driverList);
			// 关联车辆
			if (vehicle.getType().equals(Vehicle.TYPE_WHOLE)) {
				vehicleDB.setRelationVehicleId(null);
			} else {
				vehicleDB.setRelationVehicleId(vehicle.getRelationVehicleId());
			}
			// 档案扩展
			List<ArcExt> arcExtList = arcExtService.listByType(vehicle.getType());
			List<VehicleExt> vehicleExtList = new ArrayList<VehicleExt>();
			for (ArcExt arcExt : arcExtList) {
				String value = request.getParameter(arcExt.getId());
				if (StringUtils.isNotBlank(value)) {
					VehicleExt vehicleExt = new VehicleExt();
					vehicleExt.setVehicleId(vehicle.getId());
					vehicleExt.setArcExtId(arcExt.getId());
					vehicleExt.setValue(value);
					vehicleExtList.add(vehicleExt);
				}
			}
			vehicleService.update(vehicleDB, vehicleExtList);
			msg = "车辆\"" + vehicle.getPlateNumber() + "\"修改成功";
			logger.info(msg);
			logService.addLogInfo(msg, Log.OPERATE_UPDATE);
		} catch (Exception e) {
			msg = "车辆\"" + vehicle.getPlateNumber() + "\"修改失败";
			logger.error(msg, e);
			throw new BusinessException(msg, e);
		}
		return Result.success(msg);
	}

	/**
	 * 注销
	 * 
	 * @param vehicle
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "doDisable")
	@ResponseBody
	public Result doDisable(Vehicle vehicle, HttpServletRequest request) {
		String msg = null;
		try {
			String reason = request.getParameter("reason");
			// 车辆状态为已注销
			if (vehicle.getStatus().equals(Vehicle.STATUS_DISABLE)) {
				msg = "车辆\"" + vehicle.getPlateNumber() + "\"状态为已注销";
				return Result.error(msg);
			}
			// 判断车辆是否有未交费用
			List<Income> incomeList = incomeService.listByVehicleAndStatus(vehicle.getId(),
					Income.STATUS_NO);
			if (CollectionUtils.isNotEmpty(incomeList)) {
				msg = "车辆\"" + vehicle.getPlateNumber() + "\"有未交费用,无法注销";
				return Result.error(msg);
			}
			if (StringUtils.isEmpty(vehicle.getRemarks())) {
				vehicle.setRemarks("(注销原因:".concat(reason).concat(")"));
			} else {
				vehicle.setRemarks(vehicle.getRemarks().concat("(注销原因:").concat(reason).concat(")"));
			}
			vehicle.setVoidBy(LoginUserUtil.getUser().getName());
			vehicle.setVoidDate(new Date());
			vehicleService.disable(vehicle);
			msg = "车辆\"" + vehicle.getPlateNumber() + "\"注销成功";
			logger.info(msg);
			logService.addLogInfo(msg, Log.OPERATE_UPDATE);
		} catch (Exception e) {
			msg = "车辆\"" + vehicle.getPlateNumber() + "\"注销失败";
			logger.error(msg, e);
			throw new BusinessException(msg, e);
		}
		return Result.success(msg);
	}

	/**
	 * 删除
	 * 
	 * @return
	 */
	@RequestMapping(params = "doDel")
	@ResponseBody
	public Result doDel(Vehicle vehicle, HttpServletRequest request) {
		String msg = null;
		try {
			vehicle = vehicleService.get(Vehicle.class, vehicle.getId());
			// 状态是否为注销
			if (!vehicle.getStatus().equals(Vehicle.STATUS_DISABLE)) {
				msg = "车辆\"" + vehicle.getPlateNumber() + "\"必须为注销状态,才可删除";
				return Result.error(msg);
			}
			vehicleService.delete(vehicle);
			msg = "车辆\"" + vehicle.getPlateNumber() + "\"删除成功";
			logger.info(msg);
			logService.addLogInfo(msg, Log.OPERATE_DEL);
		} catch (Exception e) {
			msg = "车辆\"" + vehicle.getPlateNumber() + "\"删除失败";
			logger.error(msg, e);
			throw new BusinessException(msg, e);
		}
		return Result.success(msg);
	}

	/**
	 * 删除车辆图片
	 * 
	 * @return
	 */
	@RequestMapping(params = "doDelPic")
	@ResponseBody
	public Result doDelPic(VehiclePic vehiclePic, HttpServletRequest request) {
		String msg = null;
		try {
			vehiclePic = vehicleService.get(VehiclePic.class, vehiclePic.getId());
			vehicleService.delete(vehiclePic);
			cloudStorageService.delete(StorageConfig.bucketVehicle, vehiclePic.getThumbPath());
			cloudStorageService.delete(StorageConfig.bucketVehicle, vehiclePic.getPath());
			msg = "车辆\"" + vehiclePic.getVehicle().getPlateNumber() + "\"图片删除成功";
			logger.info(msg);
			logService.addLogInfo(msg, Log.OPERATE_DEL);
		} catch (Exception e) {
			msg = "车辆\"" + vehiclePic.getVehicle().getPlateNumber() + "\"图片删除失败";
			logger.error(msg, e);
			throw new BusinessException(msg, e);
		}
		return Result.success(msg);
	}

	/**
	 * 导出excel
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "exportXls")
	public String exportXls(Vehicle vehicle, HttpServletRequest request, HttpServletResponse response,
			DataGrid dataGrid, ModelMap modelMap) {
		CriteriaQuery cq = new CriteriaQuery(Vehicle.class, dataGrid);
		CriteriaQueryUtil.assembling(cq, vehicle, request.getParameterMap());
		List<Vehicle> vehicleList = vehicleService.listByCriteria(cq);

		modelMap.put(NormalExcelConstants.FILE_NAME, "车辆档案");
		modelMap.put(NormalExcelConstants.CLASS, Vehicle.class);
		modelMap.put(NormalExcelConstants.PARAMS,
				new ExportParams("jeecg_demo列表", "导出人:" + LoginUserUtil.getUser().getName(), "导出信息"));
		modelMap.put(NormalExcelConstants.DATA_LIST, vehicleList);
		return NormalExcelConstants.JEECG_EXCEL_VIEW;
	}

	/**
	 * 车牌校验
	 */
	@RequestMapping(params = "validPlateNumber")
	@ResponseBody
	public ValidResult validPlateNumber(HttpServletRequest request) {
		ValidResult result = new ValidResult();
		String id = request.getParameter("id");
		String plateNumber = request.getParameter("plateNumber");
		String type = request.getParameter("type");
		Vehicle vehicle = vehicleService.getByPlateNumber(plateNumber);
		if (type.equals(Vehicle.TYPE_TRAILER)) {
			// 挂车:车牌必须包含"挂"
			if (!plateNumber.contains("挂")) {
				result.setInfo("车辆类型为挂车,车牌号不正确");
				result.setStatus("n");
			}
		} else {
			// 非挂车:车牌不能包含"挂"
			if (plateNumber.contains("挂")) {
				result.setInfo("车辆类型不是挂车,车牌号不正确");
				result.setStatus("n");
			}
		}

		if (id == null) {
			// 增加
			if (vehicle != null) {
				result.setInfo("车牌号已存在");
				result.setStatus("n");
			}
		} else {
			// 修改
			if (vehicle != null && !vehicle.getId().equals(id)) {
				result.setInfo("车牌号已存在");
				result.setStatus("n");
			}
		}
		return result;
	}

	/**
	 * 编号 change
	 * 
	 * @param req
	 * @return
	 */
	@RequestMapping(params = "snChange")
	@ResponseBody
	public Result snChange(HttpServletRequest req) {
		Result result = new Result();
		String sn = req.getParameter("sn");
		Map<String, Object> attributes = new HashMap<String, Object>();
		if (StringUtils.isNotBlank(sn)) {
			List<Vehicle> vehicleList = vehicleService.listEnableBySn(sn);

			if (CollectionUtils.isNotEmpty(vehicleList)) {
				attributes.put("relationVehicleId", vehicleList.get(0).getId());
				attributes.put("relationVehiclePlateNumber", vehicleList.get(0).getPlateNumber());
			}
		}
		result.setAttributes(attributes);
		return result;
	}

	/**
	 * 责任人change
	 * 
	 * @param req
	 * @return
	 */
	@RequestMapping(params = "ownerChange")
	@ResponseBody
	public Result ownerChange(HttpServletRequest req) {
		Result result = new Result();
		String ownerId = req.getParameter("ownerId");
		Map<String, Object> attributes = new HashMap<String, Object>();
		if (StringUtils.isNotBlank(ownerId)) {
			Owner owner = ownerService.get(Owner.class, ownerId);
			Driver driver = driverService.getByPhone(owner.getPhone());
			if (driver != null) {
				attributes.put("driverId", driver.getId());
				attributes.put("driverName", driver.getName());
			}
		}
		result.setAttributes(attributes);
		return result;
	}

}
